package SunStarUtils;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import Listener.BlueToothFindListener;

/**
 * @Title: ${file_name}
 * @Description: ${todo}<请描述此文件是做什么的>
 * @data: 2016/9/7 10:38
 * @version: V1.0
 */
public class BlueToothUtil {
    private static BlueToothFindListener blueToothFindListener;
    public static BluetoothAdapter BAdapter = BluetoothAdapter.getDefaultAdapter();

    /**
     * 打开蓝牙
     */
    public static void OpenBlueTooth(){
        BAdapter.enable();
    }

    /**
     * 关闭蓝牙
     */
    public  static void CloseBlueTooth(){
        BAdapter.disable();
    }

    /**
     * 蓝牙可被发现
     */
    public static void CanFind(Context context){
        Intent intent = new Intent(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        Activity activity = (Activity) context;
        activity.startActivityForResult(intent,1);
    }
    public static BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice divice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d("BlueToothUtil", divice.getName());
//                blueToothFindListener.FindListener(divice);
            }
        }
    };

    /**
     * 发现附近设备
     * @param context
     */
    public static void FindNearDivice(Context context,BlueToothFindListener listener){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注册广播接收器，接收并处理搜索结果
        context.registerReceiver(receiver, intentFilter);
// 寻找蓝牙设备，android会将查找到的设备以广播形式发出去
        BAdapter.startDiscovery();
        blueToothFindListener = listener;
    }
}
